<template>
	<div>
		<div class="search">
		<input type="text" placeholder="输入城市名或拼音" v-model="keyword" @click="getFocus" class="search-input" name="">
	</div>
	<div class="search-content" v-show="keyword" >
		<ul>
			<li class="search-item border-bottom" v-for="item of list" :key="item.id" @click="hangleCityClick(item.name)">{{item.name}}</li>
			<li class="search-item border-bottom" v-show="hasNoData">没有找到匹配数据</li>  
			<!-- 在模板中尽量避免逻辑处理 -->
		</ul>
	</div>
	</div>
</template>

<script type="text/javascript">
	export default {
		name: 'CitySearch',
		props: {
			cities: Object
		},
		data () {
			return {
				keyword: '',
				list: [],
				timer: null,
			}
		},
		methods: {
			getFocus (e) {
				e.target.focus()
			},
			hangleCityClick(city){
				this.$store.commit('changeCity',city)
				this.$router.push('/')
			}
		},
		computed: {
			hasNoData(){
				return !this.list.length
			}
		},
		watch: {
			keyword () {
				if(this.timer) {
					clearTimeout(this.timer)
				}
				this.timer = setTimeout(()=>{
					const result = []
					if(this.keyword) {
						for (let i in this.cities) {
							this.cities[i].forEach( (item) => {
								if(item.spell.indexOf(this.keyword) > -1 || item.name.indexOf(this.keyword) >-1){
									result.push(item)
								}
							})
						}
					}else {
						this.list = []
					}
					this.list = result
				},100)
				
			}
		}
	};
</script>

<style lang="stylus" scoped>
	@import '~styles/varibles.styl'
	.search
		height: .72rem
		padding:0 .1rem
		background: $bgColor
		.search-input
			box-sizing: border-box 
			width: 100%
			height: .62rem
			line-height: .62rem
			border-radius: .06rem
			text-align: center
			color: #666
			padding: 0 .1rem
			overflow: hidden
	.search-content
		z-index: 1
		position: absolute
		top: 1.58rem
		left: 0
		right: 0
		bottom: 0
		background: #ccc
		.search-item
			height: .62rem
			line-height:.62rem
			background: #fff
			padding-left: .2rem
			color: #666
</style>
